package com.summerbird.mallchat.common.common.event.listener;

import com.summerbird.mallchat.common.common.event.UserApplyEvent;
import com.summerbird.mallchat.common.user.dao.UserApplyDao;
import com.summerbird.mallchat.common.user.service.impl.PushService;
import com.summerbird.mallchat.common.websocket.domain.vo.response.WSFriendApply;
import com.summerbird.mallchat.common.websocket.service.WebSocketService;
import com.summerbird.mallchat.common.websocket.service.adapter.WebSocketAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Slf4j
public class UserApplyListener {
    @Autowired
    private UserApplyDao userApplyDao;
    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private PushService pushService;

    // 通知对方有未读消息
    @Async
    @TransactionalEventListener(classes = UserApplyEvent.class, fallbackExecution = true)
    public void notifyFriend(UserApplyEvent event){
        Long friendUid = event.getUserApply().getId();
        Integer unReadCount = userApplyDao.getUnRead(friendUid);
        pushService.sendPushMsg(WebSocketAdapter.buildApplySend(new WSFriendApply(friendUid, unReadCount)), friendUid);
    }
}
